package com.cl.interceptor;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.http.HttpStatus;

import com.alibaba.fastjson.JSONObject;
import com.cl.annotation.IgnoreAuth;
import com.cl.entity.TokenEntity;
import com.cl.service.TokenService;
import com.cl.utils.R;

/**
 * 权限拦截器，用于验证请求的Token权限
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {

    // 定义Token的请求头名称
    public static final String LOGIN_TOKEN_KEY = "Token";

    @Autowired
    private TokenService tokenService;

    /**
     * 在请求处理之前进行拦截
     * @param request HTTP请求对象
     * @param response HTTP响应对象
     * @param handler 处理器对象
     * @return 是否继续处理请求
     * @throws Exception 异常
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 设置跨域请求的响应头
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with,request-source,Token, Origin,imgType, Content-Type, cache-control,postman-token,Cookie, Accept,authorization");
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));

        // 如果是OPTIONS请求，直接返回成功状态
        if (RequestMethod.OPTIONS.name().equals(request.getMethod())) {
            response.setStatus(HttpStatus.OK.value());
            return false;
        }

        // 检查是否有IgnoreAuth注解，表示该方法不需要权限验证
        IgnoreAuth annotation;
        if (handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(IgnoreAuth.class);
        } else {
            return true; // 非HandlerMethod直接放行
        }

        // 从请求头中获取Token
        String token = request.getHeader(LOGIN_TOKEN_KEY);

        // 如果方法标记了IgnoreAuth注解，直接放行
        if (annotation != null) {
            return true;
        }

        // 验证Token是否有效
        TokenEntity tokenEntity = null;
        if (StringUtils.isNotBlank(token)) {
            tokenEntity = tokenService.getTokenEntity(token);
        }

        // 如果Token有效，将用户信息存入Session并放行
        if (tokenEntity != null) {
            request.getSession().setAttribute("userId", tokenEntity.getUserid());
            request.getSession().setAttribute("role", tokenEntity.getRole());
            request.getSession().setAttribute("tableName", tokenEntity.getTablename());
            request.getSession().setAttribute("username", tokenEntity.getUsername());
            return true;
        }

        // 如果Token无效，返回未授权的错误信息
        sendUnauthorizedResponse(response);
        return false;
    }

    /**
     * 发送未授权的响应
     * @param response HTTP响应对象
     * @throws IOException 异常
     */
    private void sendUnauthorizedResponse(HttpServletResponse response) throws IOException {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSONObject.toJSONString(R.error(401, "请先登录")));
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }
}